/**
 * @(#)roleModifyMod.js 0.6.0 2017-10-31
 * Copyright (c) 2017, YUNXI. All rights reserved.
 * YUNXI PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */
import { parse } from 'qs'
import { message } from 'antd'
// 日期处理对象
import { isEmpty, cloneDeep } from 'lodash'
import { Link, hashHistory } from 'dva/router'
import {
  getDetail,
  addRole,
  editRole,
  getResource,
} from './roleModifyServ'
import AppBus from '../../../../utils/bus'
import config from '../../../../config/config'

//从列表中筛选出子节点和非子节点
const filterTreeNodeFromList = (list) => {
  let leafNode = [], halfNode = []
  if (list == null) {
    return {
      checkedKeys: leafNode,
      halfCheckedKeys: halfNode
    }
  }
  for (let i = 0; i < list.length; i++) {
    let temp = cloneDeep(list)
    let select = temp.splice(i, 1)
    let flag = false				//是不是有子节点指向select
    temp.forEach((item, index) => {
      if (item.parentId == select[0].id) {
        flag = true
      }
    })
    if (!flag) { leafNode.push((select[0].id).toString()) }
  }
  
  list.forEach((item, index) => {
    //leafNode没有的，就说明是非子节点
    if (leafNode.indexOf((item.id).toString()) == -1) {
      halfNode.push((item.id).toString())
    }
  })
  
  return {
    checkedKeys: leafNode,
    halfCheckedKeys: halfNode
  }
  
}

// 初始默认状态
const defultState = {
  rowIndex: '', //控制点编辑序号
  visible: false,  //过滤弹窗
  activeKey: '', //tab值
  data: {
    tableData: [],
    total: '',
  },
  search: {
    name: '',
    code: '',
    pageNum: 1,
    pageSize: 10,
  }, //查询条件
  //角色详情数据
  roleDetail: {},
  //用户列表数据
  userListData: [],
  //被选中的用户数据
  userLisDataSelect: [],
  //角色编号
  code: '',
  //角色名称
  name: '',
  applicationId: '',
  applicationName: '',
  //资源树
  resourceAll: null,
  //被选中的资源树id
  checkedKeys: [],
  halfCheckedKeys: [],
  //'add' or 'edit'
  type: '',
  roleId: '',
  saveDisabled: false,
  isShowDialog: false,
  btnOptionList: [{id: 1, text: '显示'}, {id: 2, text: '隐藏'}, {id: 3, text: '禁用'}, {id: 4, text: 'js脚本'}],
  trrOnDate: '',//选中的树id
  getBtnList: [],//按钮资源列表
  roleType: '',//角色类型
}

// 声明module
const tmpModule = {
  // namespace: 'productListModel',
  // 默认状态
  state: cloneDeep(defultState),
  //订阅数据
  subscriptions: {
    setup ({dispatch, history}) {
      return history.listen(location => {
        if (location.pathname == ('/' + tmpModule.pathname)) {
          if (location.query.type == 'edit') {
            dispatch({type: 'app/setTabTitle', payload: {title: '角色编辑', location}})
            //编辑
            dispatch({type: 'getEditData', payload: location.query})
          } else {
            dispatch({type: 'app/setTabTitle', payload: {title: '角色新增', location}})
            //新增
            dispatch({type: 'getAddData', payload: location.query})
          }
          
        }
      })
    },
  },
  //数据逻辑部分
  effects: {
    // 详情
    *getDetail({payload }, { put,select,call}) {
      let { queryList ,tableData} = yield select(state => state[tmpModule.namespace])
      let {id,index}=payload
      let currentItem=tableData.dataSource[index]
      if(tableData.dataSource[index]['currentItem']){
        currentItem=tableData.dataSource[index]['currentItem']
      }else{
        const {success,msg,data} = yield call(getDetail, {sellType: '1',id:payload.id });
        console.log('数据',success,msg,data,payload);
        if(success){
          currentItem=Object.assign(currentItem,data)
          tableData.dataSource[index]['currentItem']=data
        }
      }
      yield put({ type: 'updateStore', payload: { tableData,currentItem}});
    },
    //列表数据选择
    * onChange ({payload: {}}, {call, put, select}) {
      let {data} = yield select(state => state[tmpModule.namespace])
      yield put({type: 'updateStore', payload: {data}})
    },
    //更新数据
    * updateModel ({payload: obj}, {put, call, select}) {
      let state = yield select(state => state[tmpModule.namespace])
      yield put({
        type: 'updateStore',
        payload: {
          ...obj
        },
      })
    },
//编辑获取数据
    * getEditData ({payload}, {call, put, select}) {
      yield put({type: 'updateStore', payload: {...cloneDeep(defultState), type: payload.type, roleId: payload.roleId}})
      try {
        let result = yield call(queryRoleDetail, {
          id: payload.roleId
        })
        if ('0' !== '' + result.resultCode) {
          // message.error(result.resultMsg || '未知错误');
          return false
        }
        result.data.userList.forEach((item, index) => { item['key'] = index })
        
        let resource = yield call(getResource, {})
        
        if ('0' !== '' + resource.resultCode) {
          // message.error(resource.resultMsg || '未知错误');
          return false
        }
        
        let resourceRole = yield call(getResourceForRole, {roleId: payload.roleId})
        // if ('0' !== '' + resourceRole.resultCode) {
        // 	message.error(resourceRole.resultMsg || '未知错误');
        // 	return false;
        // }
        
        let nodeObj = filterTreeNodeFromList(resourceRole.data)
        
        //获取应用列表的按钮
        yield put({
          type: 'getBtnList',
          payload: {}
        })
        yield put({
          type: 'updateStore',
          payload: {
            roleDetail: result.data,
            userLisDataSelect: result.data.userList,
            code: result.data.code,
            name: result.data.name,
            roleType: result.data.isSharable || '',
            resourceAll: resource.data,
            checkedKeys: nodeObj.checkedKeys,
            halfCheckedKeys: nodeObj.halfCheckedKeys,
          }
        })
      } catch (e) {
        console.error(e || '网络异常，请求出错')
      }
    },
//新增进来获取数据
    * getAddData ({payload}, {call, put, select}) {
      yield put({type: 'updateStore', payload: {...cloneDeep(defultState), type: payload.type, activeKey: ''}})
      try {
        //根据应用获取按钮
        yield put({type: 'getBtnList', payload: {}})
        let resource = yield call(getResource, {})
        if ('0' !== '' + resource.resultCode) {
          // message.error(resource.resultMsg || '未知错误');
          return false
        }
        //新增的时候，不能分配已禁用的应用
        let paramObj = {}
        
        yield put({
          type: 'updateStore',
          payload: {
            resourceAll: resource.data,
          }
        })
      } catch (e) {
        console.error(e || '网络异常，请求出错')
      }
    },

//根据applicationId查询资源（选中和未选中）
    * getSource ({payload}, {call, put, select}) {
      let {data, resultCode, resultMsg} = yield call(getResource, {})
      // let { data, resultCode, resultMsg } = yield call(getResource, { applicationId: config.appId });
      if (resultCode == 0) {
        yield put({type: 'updateStore', payload: {resourceAll: data}})
        //获取应用列表的按钮
        yield put({type: 'getBtnList', payload: {}})
      }
    },

//查询被选中的资源
    * getSourceChecked ({payload}, {call, put, select}) {
      let {data, resultCode, resultMsg} = yield call(getResourceForRoleAndApp, {
        id: payload.id,
      })
      if (resultCode == 0) {
        let nodeObj = filterTreeNodeFromList(data)
        yield put({type: 'updateStore', payload: {checkedKeys: nodeObj.checkedKeys}})
      }
    },
//查询按钮资源
    * getBtnList ({payload: {applicationId}}, {call, put, select}) {
      let state = yield select(state => state[tmpModule.namespace])
      let {data, resultCode, resultMsg} = yield call(getBtnList, {roleId: state.roleId})
      if (resultCode == 0) {
        yield put({type: 'updateStore', payload: {getBtnList: data}})
      }
    },
//设置状态
    * setState ({payload}, {call, put, select}) {
      let temp = {}
      temp[payload.stateName] = payload.value
      yield put({type: 'updateStore', payload: temp})
    },
    
    * saveTreeSelectdBox ({payload}, {call, put, select}) {
      yield put({type: 'updateStore', payload: {...payload}})
    },
    
    * addOrSaveEdit ({payload}, {call, put, select}) {
      let tmpModule = yield select(state => state[tmpModule.namespace])
      let {search} = yield select(state => state[tmpModule.namespace])
      if (!(tmpModule.code || '').trim() || !(tmpModule.name || '').trim()) {
        return message.warning('角色编号、角色名称、应用为必填必选')
      }
      if (tmpModule.saveDisabled) { return }
      yield put({type: 'updateStore', payload: {saveDisabled: true}})
      let userIds = []
      tmpModule.userLisDataSelect.forEach((item) => {
        userIds.push(item.id)
      })
      try {
        let result = null
        let rids = tmpModule.checkedKeys.concat(tmpModule.halfCheckedKeys)
        let getBtnList = tmpModule.getBtnList //所有按钮列表
        let onBtnList = []//选中的资源的按钮
        
        //清除未选中资源的按钮
        getBtnList.map((item) => {
          rids.map((ritem) => {
            if (item.parentId == ritem) {
              onBtnList.push({id: item.id, defaultAction: item.defaultAction, jsContent: item.jsContent})
            }
          })
        })
        
        if (tmpModule.type == 'add') {
          let params = {
            code: tmpModule.code,
            name: tmpModule.name,
            userIds: userIds.join(','),
            resourseIds: rids.join(','),
            applicationId: tmpModule.applicationId,
            subElements: JSON.stringify(onBtnList)
          }
          if (tmpModule.roleType) {
            params.isSharable = tmpModule.roleType
          }
          
          result = yield call(addRole, params)
        } else {
          result = yield call(updateRole, {
            id: tmpModule.roleId,
            code: tmpModule.code,
            name: tmpModule.name,
            userIds: userIds.join(','),
            resourseIds: rids.join(','),
            applicationId: tmpModule.applicationId,
            subElements: JSON.stringify(onBtnList),
          })
        }
        if (result.resultCode == 0) {
          message.success('操作成功')
          //关闭新增、编辑叶签
          AppBus.emit('closeTab', {
            key: MODULE_TO_ROUTES['tmpModule'].urlArray[1],
            cbf: () => {
              // 这里编写你的下一步逻辑，返回店铺列表
              hashHistory.push(MODULE_TO_ROUTES['tmpModule'].urlArray[0])
            }
          })
          // hashHistory.push(MODULE_TO_ROUTES['tmpModule'].urlArray[0]);
        }
      } catch (e) {
        console.error(e || '网络异常，请求出错')
      }
      search.pageNum = 1
      search.pageSize = 10
      yield put({type: 'updateStore', payload: {saveDisabled: false, search}})
    },
  },
//更新数据到state
  reducers: {
    updateStore (preState, action) {
      return Object.assign({}, preState, action.payload)
    }
  }
}
export default tmpModule
